package com.pvdnc.xdynamic.loader;

import android.annotation.SuppressLint;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.util.Log;

import com.pvdnc.xdynamic.loader.mirror.PackageParser;
import com.pvdnc.xdynamic.loader.mirror.PackageParserMarshmallow;
import com.pvdnc.xdynamic.loader.mirror.android.content.pm.PackageUserState;
import com.pvdnc.xdynamic.loader.module.ModuleDir;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@SuppressLint("PrivateApi")
public class PackageParserUtils {
    private static final String TAG=PackageParserUtils.class.getSimpleName();

    private static Class<?> getParserClass() throws ClassNotFoundException {
        return Class.forName("android.content.pm.PackageParser");
    }

    public static Object newInstance() throws Exception {
        Class<?> ppClass = getParserClass();
        return ppClass.newInstance();
    }

    public static Object parsePackage(File apkFile) throws Exception {
        Object pp= newInstance();
        Object pkg= PackageParserMarshmallow.parsePackage.call(pp,apkFile,0);
        Log.d(TAG,"parsed pkg:"+pkg);
        return pkg;
    }

    public static ApplicationInfo generateApplicationInfo(Object pkg) throws Exception {
        Class<?> pkgClass=pkg.getClass();
        Field appInfoField=pkgClass.getDeclaredField("applicationInfo");
        appInfoField.setAccessible(true);
        ApplicationInfo appInfo= (ApplicationInfo) appInfoField.get(pkg);
        Log.d(TAG,"app info:\n\t"+appInfo);
        return appInfo;
    }

    public static List<ActivityInfo> getActivityInfoList(Object pkg) throws Exception{
        List<ActivityInfo> activityInfoList=new ArrayList<>();

        Class<?> pkgClass=pkg.getClass();
        Field pkgActivityListField=pkgClass.getDeclaredField("activities");
        pkgActivityListField.setAccessible(true);
        List pkgActivityList= (List) pkgActivityListField.get(pkg);
        for (Object pkgActivity:pkgActivityList){
            Field infoField=pkgActivity.getClass().getDeclaredField("info");
            infoField.setAccessible(true);
            ActivityInfo activityInfo= (ActivityInfo) infoField.get(pkgActivity);
            activityInfoList.add(activityInfo);
        }
        return activityInfoList;
    }
}
